/**
 * Created by QB on 2014/12/10.
 */
package {
    import flash.filesystem.File;
    import flash.utils.ByteArray;
    
    import Qbase.utils.calculate.QFileUtil;
    
    import lzm.starling.swf.Swf;
    import lzm.starling.swf.SwfAssetManager;
    
    import starling.display.Image;
    import starling.textures.Texture;

    public class XX2AssetManager extends SwfAssetManager
    {
        /**
         * 使用ATF资源类型
         * "no"			不使用
         * "all"		全平台
         * "android"	仅安卓
         * "ios"		仅IOS
         */
        private const ATF_TYPE						: String = "no";

//        /**SWF资源*/
//        private var _swfAssetManager            : SwfAssetManager;
        /**已加载的swf资源名称数组*/
        private var _vecLoadedSwfName               : Vector.<String> = new <String>[];
        /**已加载的其他资源url数组*/
        private var _vecLoadedOtherUrl              : Vector.<String> = new <String>[];


        public function XX2AssetManager(scaleFactor:Number = 1, useMipmaps:Boolean = false)
        {
            super(scaleFactor, useMipmaps);

            this.verbose = true;
//            _swfAssetManager = new SwfAssetManager(scaleFactor, useMipmaps);
//            _swfAssetManager.verbose = true;
        }

        /**添加基本资源*/
        public function addBaseResource( $onComplete:Function = null ):void
        {
            var file:File = File.applicationDirectory;
            //			/**
            var appDataFileURLList			: Array = QFileUtil.getAllFileUrlByDirectory( file.url, "appData", ["xml","csv"] );
            var soundFileUrlList			: Array = QFileUtil.getAllFileUrlByDirectory( file.url, "sound", ["mp3"] );
            var gameDataFileURLList			: Array = QFileUtil.getAllFileUrlByDirectory( file.url, "gameData", ["xml"] );
            var assetDataFileURLList		: Array = QFileUtil.getAllFileUrlByDirectory( file.url, "assetData", ["xml"] );
            var bitmapFontFileURLList		: Array = QFileUtil.getAllFileUrlByDirectory( file.url, "bitmapFont", ["png", "xml", "fnt"] );
//            var texturesBaseFileURLList		: Array;
//            var resList:Array = [];
//            var otherFileList:Array = appDataFileURLList.concat(
//                    soundFileUrlList. concat(
//                            gameDataFileURLList.concat(
//                                    assetDataFileURLList.concat(
//                                            bitmapFontFileURLList
//                                    )
//                            )
//                    )
//            );

            this.enqueueOtherAssets(
                    appDataFileURLList,
                    soundFileUrlList,
                    gameDataFileURLList,
                    assetDataFileURLList,
                    bitmapFontFileURLList
            );
            this.loadQueue( function($ratio:Number):void
            {
               if ($ratio == 1)
               {
                   addResource( ["base"], $onComplete );
               }
            });

//            switch (ATF_TYPE)
//            {
//                case "no":
////                    resList = resList.concat( getResFileByDirectory( file.url, "textures/base", ["png","xml","bytes"] ) );
//                    break;
//                case "all":
////                    resList = resList.concat( getResFileByDirectory( file.url, "atf/base", ["png","xml","bytes","atf"] ) );
//                    break;
//                case "android":
////                    resList = resList.concat( getResFileByDirectory( file.url, "androidATF/base", ["png","xml","bytes","atf"] ) );
//                    break;
//            }

//            this.enqueueOtherAssets(
//                    appDataFileURLList
//                    , soundFileUrlList
//                    , gameDataFileURLList
//                    , assetDataFileURLList
//                    , bitmapFontFileURLList
//            );
//            this.loadQueue( function($ratio:Number):void
//            {
//                if ($ratio == 1)
//                {
//                    if ($onComplete)
//                    {
//                        $onComplete();
//                    }
//                }
//            });
        }

        /**添加资源*/
        public function addResource( $resPackageNameList:Array, $onCompleteCallBack:Function = null ):void
        {
            if (!$resPackageNameList)
            {
                $onCompleteCallBack();
                return;
            }

            var file:File = File.applicationDirectory;
            var resList:Array = [];
            var i:int;
            for (i = 0; i < $resPackageNameList.length; i++)
            {
                switch (ATF_TYPE)
                {
                    case "no":
                        resList.push( getResFileByDirectory( file.url, "textures/" + $resPackageNameList[i], ["png","xml","bytes"] ) );
                        break;
                    case "all":
                        resList.push( getResFileByDirectory( file.url, "atf/" + $resPackageNameList[i], ["png","xml","bytes","atf"] ) );
                        break;
                    case "android":
                        resList.push( getResFileByDirectory( file.url, "androidATF/" + $resPackageNameList[i], ["png","xml","bytes","atf"] ) );
                        break;
                }
            }

            var j:int;
            for (i = 0; i < resList.length; i++)
            {
                var swfFileList:Array = resList[i][0];
                var otherFileList:Array = resList[i][1];

                if (swfFileList)
                {
                    for (j = 0; j < swfFileList.length; j++)
                    {
                        var swfName:String = swfFileList[j][0];
                        var swfResList:Array = swfFileList[j][1];

                        if (_vecLoadedSwfName.indexOf(swfName) != -1)       //已加载，跳过
                        {
                            continue;
                        }
                        if (swfName.indexOf("fps_") == 4)
                        {
                            var tempStr:String = swfName.substr(8);         //去除"swf_fps_"
                            var fps:uint = uint(tempStr.substr(0, tempStr.indexOf("_")));
                            this.enqueue(swfName, swfResList, fps);
                        }
                        else
                        {
                            this.enqueue(swfName, swfResList);
                        }
                    }
                }
                if (otherFileList)
                {
                    for (j = 0; j < otherFileList.length; j++)
                    {
                        for (var k:int = 0; k < otherFileList[j].length; k++)
                        {
                            if (_vecLoadedOtherUrl.indexOf( otherFileList[j][k].name ) != -1)   //已加载，跳过
                            {
                                continue;
                            }
                            this.enqueueOtherAssets( otherFileList[j][k] );
                        }
                    }
                }
            }

            _debugRes = resList;
//            _swfAssetManager.loadQueue( function($ratio:Number):void
            this.loadQueue( function($ratio:Number):void
            {
//                trace( "resLoading...", $ratio );
                if ($ratio == 1)
                {
                    var ii:int;
                    var jj:int;
                    var kk:int;
                    for (ii = 0; ii < resList.length; ii++)
                    {
                        var swfFileList:Array = resList[ii][0];
                        var otherFileList:Array = resList[ii][1];

                        if (swfFileList)
                        {
                            for (jj = 0; jj < swfFileList.length; jj++)
                            {
                                var swfName:String = swfFileList[jj][0];
                                _vecLoadedSwfName.push(swfName);
                            }
                        }
                        if (otherFileList)
                        {
                            for (jj = 0; jj < otherFileList.length; jj++)
                            {
                                for (kk = 0; kk < otherFileList[jj].length; kk++)
                                {
                                    _vecLoadedOtherUrl.push(otherFileList[jj][kk].name);
                                }
                            }
                        }
                    }

                    if ($onCompleteCallBack)
                    {
                        $onCompleteCallBack();
                    }
                }
            });
        }
        private var _debugRes:Array;

        /**移除资源*/
        public function removeResource( $resPackageNameList:Array, $onCompleteCallBack:Function ):void
        {
            if (!$resPackageNameList)
            {
                return;
            }

            var file:File = File.applicationDirectory;
            var resList:Array = [];
            var i:int;
            for (i = 0; i < $resPackageNameList.length; i++)
            {
                switch (ATF_TYPE)
                {
                    case "no":
                        resList.push( getResFileByDirectory( file.url, "textures/" + $resPackageNameList[i], ["png","xml","bytes"] ) );
                        break;
                    case "all":
                        resList.push( getResFileByDirectory( file.url, "atf/" + $resPackageNameList[i], ["png","xml","bytes","atf"] ) );
                        break;
                    case "android":
                        resList.push( getResFileByDirectory( file.url, "androidATF/" + $resPackageNameList[i], ["png","xml","bytes","atf"] ) );
                        break;
                }
            }

            var j:int;
            for (i = 0; i < resList.length; i++)
            {
                var swfFileList:Array = resList[i][0];
                var otherFileList:Array = resList[i][1];

                if (swfFileList)
                {
                    for (j = 0; j < swfFileList.length; j++)
                    {
                        var swfName:String = swfFileList[j][0];
                        var swfResList:Array = swfFileList[j][1];

                        this.removeSwf( swfName );
                        _vecLoadedSwfName.splice( _vecLoadedSwfName.indexOf( swfName ), 1 );
                    }
                }
                if (otherFileList)
                {
                    for (j = 0; j < otherFileList.length; j++)
                    {
                        for (var k = 0; k < otherFileList[j].length; k++)
                        {
                            otherAssets.removeTextureAtlas( otherFileList[j][k].name );
                            _vecLoadedOtherUrl.splice( _vecLoadedOtherUrl.indexOf( otherFileList[j][k].name ), 1 );
                        }
                    }
                }
            }
//            var file:File = File.applicationDirectory;
//            var fileList:Array = [];
//            var i:int;
//            for (i = 0; i < $resPackageNameList.length; i++)
//            {
//                switch (ATF_TYPE)
//                {
//                    case "no":
//                        fileList = fileList.concat( QFileUtil.getAllFileByDirectory( file.url, "textures/" + $resPackageNameList[i], ["png","xml","bytes"] ) );
//                        break;
//                    case "all":
//                        fileList = fileList.concat( QFileUtil.getAllFileByDirectory( file.url, "atf/" + $resPackageNameList[i], ["png","xml","bytes", "atf"] ) );
//                        break;
//                    case "android":
//                        fileList = fileList.concat( QFileUtil.getAllFileByDirectory( file.url, "androidATF/" + $resPackageNameList[i], ["png","xml","bytes", "atf"] ) );
//                        break;
//                }
//            }
//            for (i = fileList.length - 1; i >= 0; i--)
//            {
//                file = fileList[i];
//                var resName:String = file.name.replace( file.type, "" );
//                var loadedURLIndex:int = _aLoadedURL.indexOf( file.url );
//                if (loadedURLIndex != -1)
//                {
//                    _aLoadedURL.splice( _aLoadedURL.indexOf( file.url ), 1 );
//                    print( "移除资源：" + file.name );
//                    this.removeTextureAtlas( resName );
//                }
//            }


        }

        /**
         * 加载文件夹下所有子文件
         * return   [[swf资源[swf名,[资源列表]],[其他资源]]
         */
        private function getResFileByDirectory( $rootPath:String, $directory:String = "", $extensionFilter:Array = null, $swfFileList:Array = null, $otherFileList:Array = null ):Array
        {
            var swfFileList:Array;
            if ($swfFileList)
            {
                swfFileList = $swfFileList;
            }
            else
            {
                swfFileList = [];
            }
            var otherFileList:Array = $otherFileList ? $otherFileList : [];

            //识别当前目录是否为 StarlingSWF资源目录
            var isSwfDirctory:Boolean;
            if ($directory.indexOf("swf_") == 0)
            {
                isSwfDirctory = true;
            }
            else
            {
                isSwfDirctory = false;
            }
            var i:int;
            var j:int;
            var fileDirectory:File;
            if ($rootPath.charAt($rootPath.length-1) != "/")
            {
                fileDirectory = new File( $rootPath + "/" + $directory );
            }
            else
            {
                fileDirectory = new File( $rootPath + $directory );
            }
            try
            {
                var fileList:Array = fileDirectory.getDirectoryListing();
                var tempSwfFileList:Array = [];
                var tempOtherFileList:Array = [];
                for (i = 0; i < fileList.length; i++)
                {
                    trace( fileList.length, i, fileList[i].name, fileList[i].isDirectory );
                    if (fileList[i].isDirectory && !isSwfDirctory)      //子一级是文件夹并且当前级不是swf文件夹，则需要继续迭代子级文件夹
                    {
                        getResFileByDirectory( fileDirectory.url, fileList[i].name, $extensionFilter, swfFileList, otherFileList );
                    }
                    else
                    {
                        //是文件，进行过滤
                        for (j = fileList.length - 1; j > 0; j--)
                        {
                            var file:File = fileList[j];
                            if (!file.isDirectory && $extensionFilter && $extensionFilter.indexOf(file.extension) == -1)			//如果有筛选器，并且不是文件夹 且文件类型不在筛选器中，则移除
                            {
                                fileList.splice( j , 1 );
//                                i--;
                            }
                        }

                        //根据当前目录类型将文件信息放入列表
                        if (isSwfDirctory)
                        {
                            tempSwfFileList.push( fileList[i] );
                        }
                        else
                        {
                            tempOtherFileList.push( fileList[i] );
                        }
                    }
                }
                if (tempSwfFileList.length > 0)
                {
                    swfFileList.push( [$directory, tempSwfFileList ]);
                }
                if (tempOtherFileList.length > 0)
                {
                    otherFileList.push( tempOtherFileList );
                }
            }
            catch ($e:Error)
            {
                trace( $e );
                return [];
            }
            return [swfFileList, otherFileList];
        }

        /**获得贴图数组*/
        public function getTextures( $prefix:String ):Vector.<Texture>
        {
            return otherAssets.getTextures( $prefix );
        }

        /**获得贴图*/
        public function getTexture( $name:String ):Texture
        {
            var tex:Texture = otherAssets.getTexture( $name );
            if (tex)
            {
                return tex;
            }
            else
            {
                var img:Image = super.createImage( $name );
                for each(var swf:Swf in _swfs)
                {
                    tex = swf.assets.getTexture($name)
                    if (tex)
                    {
                        return tex;
                    }
                }
            }
            return null;
        }

        /**获得XML*/
        public function getXml( $name:String ):XML
        {
            return otherAssets.getXml( $name );
        }

        /**获得字节数据*/
        public function getByteArray( $name:String ):ByteArray
        {
            return otherAssets.getByteArray( $name );
        }
    }
}
